import os
import shutil
import re

EXAMPLES_DIR = os.path.join(os.path.dirname(__file__), '../config/examples')
TARGET_DIR = os.path.join(os.path.dirname(__file__), '../config')

# 需要去除注释的 yaml 文件名
YAML_FILES = ['config.yaml']

def strip_yaml_comments(src_path, dst_path):
    with open(src_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    with open(dst_path, 'w', encoding='utf-8') as f:
        for line in lines:
            # 保留空行和缩进，去除 # 及其后的注释
            if '#' in line:
                # 只保留 # 之前内容
                idx = line.index('#')
                pure = line[:idx].rstrip()
                if pure.strip() == '':
                    f.write('\n')
                else:
                    f.write(pure + '\n')
            else:
                f.write(line)

def init_config_from_examples():
    for fname in os.listdir(EXAMPLES_DIR):
        if not fname.endswith('.example'):
            continue
        target_name = fname.replace('.example', '')
        src_path = os.path.join(EXAMPLES_DIR, fname)
        dst_path = os.path.join(TARGET_DIR, target_name)
        if os.path.exists(dst_path):
            continue  # 已存在不覆盖
        if target_name in YAML_FILES:
            strip_yaml_comments(src_path, dst_path)
        else:
            shutil.copyfile(src_path, dst_path)
        print(f'已生成默认配置: {dst_path}')

if __name__ == '__main__':
    init_config_from_examples()
    print('所有默认配置已生成（如已存在则跳过）')
